<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <div class="download-zone">
      <!-- 搜索条件栏 -->
      <el-form ref="form" :model="query" label-width="80px" :inline="true">
        <el-form-item label="文件名称">
          <el-input v-model="query.subject" placeholder="请输入文件名称" clearable style="width: 300px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item>

        <!-- 按钮 -->
      </el-form>
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="success" @click="addFile">添加文件</el-button>
      </div>
      <!-- 文件列表表格 -->
      <el-table :data="tableData" border stripe style="margin-top: 0px;" :header-cell-style="{
    background: '#f5f7fa',
    color: '#606266',
    fontWeight: 'bold',
    textAlign: 'center',
    height: '50px',
    fontSize: '14px'
  }" :row-style="{ height: '55px' }" :cell-style="{ textAlign: 'center' }" highlight-current-row
        class="file-table">
        <el-table-column label="文件名称" prop="subject" min-width="180" show-overflow-tooltip />
        <el-table-column label="文件分类" prop="fileTag" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag size="small" effect="plain" type="info">{{ getFileType(row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件价格" prop="price" width="100" align="center" />
        <el-table-column label="文件类型" prop="fileType" width="100">
          <template #default="{ row }">
            <el-tag size="small" type="success">{{ row.fileType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下载次数" prop="downloadCount" width="100">
          <template #default="{ row }">
            <span class="download-count">{{ row.downloadCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" prop="createTime" width="100" align="center" />

        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row, $index }">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="downloadFile(row)" :icon="Download">下载</el-button>
              <el-button size="small" type="warning" @click="editFile(row, $index)" :icon="Edit">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteFiles(row)" :icon="Delete">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        v-model:currentPage="query.pageNum" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]" :total="query.total" class="pagination-container" />

      <!-- 文件编辑抽屉 -->
      <el-drawer v-model="fileDialogVisible" :title="fileDialogMode === 'add' ? '添加文件' : '编辑文件'" size="70%"
        direction="rtl">
        <div class="file-editor">
          <!-- 文件类型筛选按钮组 -->
          <div class="filter-buttons" style="margin-bottom: 20px;">
            <el-radio-group v-model="fileForm.category" @change="handleFileTypeChange">
              <el-radio-button :value="1">笔试</el-radio-button>
              <el-radio-button :value="2">面试</el-radio-button>
              <el-radio-button :value="99">其他</el-radio-button>
            </el-radio-group>
          </div>

          <el-form :model="fileForm" :rules="fileFormRules" ref="fileFormRef" label-width="130px">

            <el-form-item label="文件分类(必填)" v-if="fileForm.category != '99'">
              <tagList v-if="fileForm.category == '2'" :defaultActive="activeListObj.defaultActive"
                :defaultSubActive="activeListObj.defaultSubActive"
                :defaultChildActive="activeListObj.defaultChildActive" @change="handleMainTagChange"
                @subChange="handleSubTagChange" @childChange="handleChildTagChange" :tagList="tagListData" />
              <tagList1 v-if="fileForm.category == '1'" :checkLists="checkList"
                :defaultActive="activeListObj.defaultActive" :defaultSubActive="activeListObj.defaultSubActive"
                :defaultChildActive="activeListObj.defaultChildActive" @change="handleMainTagChange"
                @subChange="handleSubTagChange" @childChange="handleChildTagChange" :tagList="tagListData" />

            </el-form-item>
            <el-form-item label="文件" prop="fileUrl">
              <custom-upload @success="handleSuccess" v-model="fileForm.fileUrl" :limit="1" :action="uploadUrl"
                :data="{}" :headers="{}" :multiple="false" class="custom-upload" type="expand" itemType="text"
                accept=".pdf,.docx,.doc" />
            </el-form-item>
            <!-- v-if="fileForm.fileType == 'docx' || fileForm.fileType == 'doc'" -->
            <el-form-item label="pdf文件" prop="downloadPdfUrl"
              v-if="fileForm.fileType == 'docx' || fileForm.fileType == 'doc'">
              <custom-upload @success="handleSuccess1" v-model="fileForm.downloadPdfUrls" :limit="1" :action="uploadUrl"
                :data="{}" :headers="{}" :multiple="false" class="custom-upload" type="expand" itemType="text"
                accept=".pdf" />
            </el-form-item>
            <el-form-item label="文件名称" prop="subject">
              <el-input v-model="fileForm.subject" placeholder="请输入文件名称" />
            </el-form-item>
            <el-form-item label="文件价格" prop="price">
              <el-input-number v-model="fileForm.price" :min="0" placeholder="请输入文件价格" />
            </el-form-item>
          </el-form>

          <div class="drawer-footer" style="margin-top: 30px; text-align: right;">
            <el-button @click="closeDrawer">取消</el-button>
            <el-button type="primary" :loading="loading" @click="saveFile">
              {{ loading ? '正在生成预览文件，请稍等...' : '保存' }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </el-card>

</template>

<script setup>
import { getInterViewItem, writeTagList, interviewTagList, getWriteTagOptions, getWriteChildTagOptions } from './utils/index';
import { ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getFileList, uploadFile, deleteFile } from '@/api/zhaokao/downloadZone';
import tagList from './components/tagListBox.vue';
import tagList1 from './components/tagListBox1.vue';
import customUpload from '@/components/CustomUpload/index.vue';
import { serverDefaultCfg } from '@/common/http/config';
import { Download, Edit, Delete } from '@element-plus/icons-vue';
const uploadUrl = process.env.VUE_APP_SERVER_HOST + '/examResources/upload';
// 响应式数据
const writeChildTypeOptions = ref([]);
const tableData = ref([
]);
const loading = ref(false);
const activeListObj = ref({
  defaultActive: -1,
  defaultSubActive: -1,
  defaultChildActive: -1
})
// 分页查询参数
const query = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,

})

// 抽屉和对话框控制
const fileDialogVisible = ref(false);
const fileDialogMode = ref('add');

// 表单引用
const fileFormRef = ref();

// 表单数据
const fileForm = ref({
  subject: '',
  fileTag: [],
  category: '',
  downloadCount: 0,
  downloadPdfUrls: [],
  fileUrl: [],
});

const tagListData = ref([]);
watch(() => fileForm.value.category, () => {
  if (fileForm.value.category == '1') {
    tagListData.value = [];
    tagListData.value = writeTagList;
    console.log(tagListData.value);
  } else if (fileForm.value.category == '2') {
    tagListData.value = [];
    tagListData.value = interviewTagList;
    console.log(tagListData.value);

  }
}, { deep: true })

const currentEditIndex = ref(-1);

// 表单验证规则
const fileFormRules = {
  subject: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择文件分类', trigger: 'change' }],
  fileTag: [{ required: true, message: '请选择文件分类', trigger: 'change' }],
};


// 文件管理相关方法
const addFile = () => {
  fileDialogMode.value = 'add';
  checkList.value = []
  fileForm.value = {
    subject: '',
    category: '',
    fileUrl: [],
    downloadPdfUrls: [],
  };
  activeListObj.value = {
    defaultActive: -1,
    defaultSubActive: -1,
    defaultChildActive: -1
  }
  currentEditIndex.value = -1;
  fileDialogVisible.value = true;
};
const checkList = ref([]);
const editFile = (file, index) => {
  console.log(file);
  fileDialogMode.value = 'edit';
  fileForm.value = file;
  fileForm.value.fileUrl = [{
    url: file.downloadUrl,
    downloadUri: file.downloadUrl,
    name: file.subject
  }]
  if (file.downloadPdfUrl) {
    fileForm.value.downloadPdfUrls = [{
      url: file.downloadPdfUrl,
      downloadUri: file.downloadPdfUrl,
      name: file.subject
    }]
  }

  fileForm.value.category = +file.category
  activeListObj.value.defaultSubActive = -1
  checkList.value = []


  // 笔试,
  if (file.category == '1') {
    console.log(writeTagList.findIndex(item => item.value == file.subCategory));

    activeListObj.value.defaultActive = writeTagList.findIndex(item => item.value == file.subCategory);
    if (file.sort.split('_').length > 2) {
      checkList.value[0] = file.sort
      activeListObj.value.defaultSubActive = -1

    } else {
      checkList.value = []
      activeListObj.value.defaultSubActive = writeTagList[activeListObj.value.defaultActive].subTags.findIndex(item => item.value == file.sort)
      console.log(activeListObj.value.defaultSubActive);

    }
  }
  // 面试
  if (file.category == '2') {
    activeListObj.value.defaultActive = (+file.subCategory) - 1
  }

  currentEditIndex.value = index;
  fileDialogVisible.value = true;
};
const handleSuccess = (res) => {
  console.log(111111);
  console.log(res.data);
  fileForm.value.downloadUrl = res.data.downloadUri
  fileForm.value.fileType = res.data.fileType
  fileForm.value.subject = res.data.fileName
  // fileForm.value.fileUrl[0].downloadUri = res.data
}
const handleSuccess1 = (res) => {
  console.log(111111);
  console.log(res.data);
  fileForm.value.downloadPdfUrl = res.data.downloadUri
  // fileForm.value.fileUrl[0].downloadUri = res.data
}
const deleteFiles = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除此文件吗？删除后不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    deleteFile(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getList();
      }
    })

  } catch {
    // 用户取消删除
  }
};

const handleFileTypeChange = () => {
  fileForm.value.fileTag = [];
  // 清空子标签
  activeListObj.value.defaultSubActive = -1;
  activeListObj.value.defaultChildActive = -1;
};
const closeDrawer = () => {
  fileDialogVisible.value = false;
  getList();
}

const saveFile = () => {
  console.log(fileForm.value);
  // 判断是否有文件分类
  if (fileForm.value.category == '') {
    ElMessage.warning('请填写文件分类');
    return;
  }
  if (!fileForm.value.downloadUrl) {
    ElMessage.warning('请上传文件');
    return;
  }
  if (fileForm.value.fileType == 'doc' || fileForm.value.fileType == 'docx') {
    if (!fileForm.value.downloadPdfUrl) {
      ElMessage.warning('请上传pdf文件');
      return;
    }
  }

  loading.value = true;


  // fileForm.value.downloadUrl = fileForm.value.fileUrl[0].downloadUri
  // fileForm.value.fileType = fileForm.value.fileUrl[0].name.split('.')[1]
  // fileForm.value.subject = fileForm.value.fileUrl[0].name.split('.')[0]
  // 验证表单
  fileFormRef.value.validate((valid) => {
    if (valid) {
      uploadFileInTerView();
    } else {
      ElMessage.warning('请填写必填项');
      return false;
    }
  });
};
const uploadFileInTerView = async () => {
  const obj = {
    id: fileForm.value.id,
    subject: fileForm.value.subject,
    category: fileForm.value.category,
    subCategory: fileForm.value.subCategory,
    sort: fileForm.value.sort,
    downloadUrl: fileForm.value.downloadUrl,
    downloadPdfUrl: fileForm.value.downloadPdfUrl,
    fileType: fileForm.value.fileType,
    price: fileForm.value.price || 0
  }
  uploadFile(obj).then(res => {
    if (res.code === 200) {
      ElMessage.success('上传成功');
      fileDialogVisible.value = false;
      getList();
      loading.value = false;
    }
  }).catch(() => {
    loading.value = false;
  });
};


// 分页查询
const handleSizeChange = (val) => {
  query.value.pageSize = val;
  getList();
}

const handleCurrentChange = (val) => {
  query.value.pageNum = val;
  getList();
}
// 分页查询
const getList = async () => {
  const res = await getFileList(query.value);
  console.log(res);
  if (res.code === 200) {
    tableData.value = res.data.records;
    query.value.total = res.data.total;
  }
}
getList();


const handleMainTagChange = (tag) => {
  console.log('🎯 初始主标签:', tag) // "行测"
  fileForm.value.subCategory = tag.value
}
const writeTestObj = ref({})
const handleSubTagChange = (subTag) => {
  console.log('🎯 初始子标签:', subTag) // "言语理解与表达"
  fileForm.value.sort = subTag.value
}

const handleChildTagChange = (childTag) => {
  fileForm.value.sort = childTag[0]

  console.log('🎯 初始三级标签:', childTag[0]) // "词语填空"
}


const getFileType = (rows) => {
  const row = JSON.parse(JSON.stringify(rows))
  if (row.category == 99) {
    return '其他'
  }
  if (row.subCategory == 'Z') {
    return '笔试-其他'
  }

  let fileType = ""
  let type = row.category == 1 ? '笔试' : '面试'
  let subCategory = ''
  let sort = ''
  if (type == '笔试') {
    if (row.subCategory) {
      subCategory = writeTagList.find(item => item.value == row.subCategory)?.name
    }
    if (row.sort) {

      if (row.sort.split('_').length > 2) {
        let sort1 = writeTagList.find(item => item.value == row.subCategory)?.
          subTags.find(item => item.value == (row.sort.split('_')[0] + '_' + row.sort.split('_')[1]))?.name

        let sort2 = writeTagList.find(item => item.value == row.subCategory)?.
          subTags.find(item => item.value == (row.sort.split('_')[0] + '_' + row.sort.split('_')[1]))?.
          children.find(item => item.value == row.sort)?.name
        return `${type}-${subCategory}-${sort1}-${sort2}`

      } else {
        sort = writeTagList.find(item => item.value == row.subCategory)?.subTags.find(item => item.value == row.sort)?.name
        return `${type}-${subCategory}-${sort}`

      }
    }
  }
  if (type == '面试') {
    if (row.subCategory) {
      subCategory = interviewTagList.find(item => item.value == row.subCategory)?.name
    }
    return `${type}-${subCategory}`
  }



}
const downloadFile = (row) => {
  // 创建a标签
  let a = document.createElement('a')
  a.href = row.downloadUrl
  a.download = row.subject
  a.click()

}

</script>

<style lang="scss" scoped>
.download-zone {
  padding: 0px;

  .operation-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .file-table {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    overflow: hidden;

    :deep(.el-table__row) {
      transition: all 0.3s;

      &:hover {
        background-color: #f0f9eb !important;
      }
    }

    :deep(.el-button) {
      padding: 6px 12px;
      margin: 0 4px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 8px;
  }

  .download-count {
    font-weight: bold;
    color: #409EFF;
    background: rgba(64, 158, 255, 0.1);
    padding: 2px 8px;
    border-radius: 10px;
    display: inline-block;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }
}

.file-editor {
  padding: 20px;

  .filter-buttons {
    margin-bottom: 20px;
  }

  .drawer-footer {
    margin-top: 30px;
    text-align: right;
  }
}

:deep(.el-drawer__body) {
  padding: 0;
}
</style>
